<template>
	<view>
		<view class="pure_top">
			<view class="pos_r pw100 ph100 plr30 pt30 bsb b-primary">
				<view class="flex_a">
					<view class="w120 h120 bf border-r50p" v-if="token && userInfo.phone" @click="buttonPhone">
						<image :src="userInfo.head_img || '/static/default_avatar.png'" mode="widthFix"
							style="width: 120upx;"></image>
					</view>
					<view class="w120 h120 bf border-r50p" v-else @click="buttonPhone">
						<image :src="'/static/default_avatar.png'" mode="widthFix" style="width: 120upx;"></image>
					</view>
					<view class="flex1 flex_a pl10 cf" v-if="token && userInfo.phone">
						<view class="flex1" @click="buttonPhone">
							<view class="h60">{{ userInfo.nick_name }}</view>
							<view>账号：{{ userInfo.phone }}</view>
						</view>
						<view class="w60 h60" @click="routerLink({ path: '/pages/user/center/person' }, true)">
							<image src="/static/eyes.png" mode="widthFix" style="width: 60upx;"></image>
						</view>
					</view>
					<view class="flex1 pl20 cf ft30" v-else>未登录</view>
				</view>
			</view>
		</view>
		<view class="center_c plr30 c6">
			<!-- 我的钱包 -->
			<view class="mb30 bf border-r2 shadow">
				<view class="flex_a  tac" v-if="token && userInfo.phone">
					<view class="displayss">
						<view class="flex1 bdr_f" @click="RechargeImmediately"
							style="font-weight: 700;color: #00a2ea;background-color: #ccc;height: 100%;background-color: #fff;">
							<view class="pb10 ft36" style="padding-top: 10upx;font-size: 40upx;">
								<image src="/static/sscharge.png" mode="widthFix" style="width: 66upx;height: 30upx;">
							</view>
							<view class="ft26" style="padding-bottom: 20upx;font-size: 40upx;">立即充值
							</view>
						</view>

						<view class="flex1 bdr_f"
							style="font-weight: 700;color: #00a2ea;height: 100%;background-color: #eee;"
							@click="nomeybaoFn">
							<view class="pb10 ft36" style="padding-top: 20upx;font-size: 40upx;">
								{{ (list.balance + list.giveMoney).toFixed(2) || '0.00' }}
							</view>
							<view class="ft26" style="padding-bottom: 20upx;font-size: 40upx;">我的钱包</view>
						</view>
					</view>
				</view>
				<view class="flex_a h140 tac" v-else>
					<view class="flex1 bdr_f" style="height: 100%;padding-top: 20upx;">
						<view class="pb10 ft36">--</view>
						<view class="ft26">立即充值</view>
					</view>
					<view class="flex1 bdr_f" style="height: 100%;background-color: #eee;padding-top: 20upx;">
						<view class="pb10 ft36">--</view>
						<view class="ft26">我的钱包</view>
					</view>
				</view>
			</view>

			<view class="one">
				<u-row gutter="16" justify="flex-start" align="top">
					<u-col class="mgbt" text-align="center" span="4" v-for="(menu, index) in menuList" :key="index">
						<view class="mgbt"
							v-if="menu.isOpen&&!menu.isLogin ? true : menu.isOpen && yesLogin ? true :false"
							@click="routerListFn(menu)">
							<view class="flex_aj h90">
								<image :src="menu.icon" mode="widthFix" :style="{ width: menu.iconSize.w + 'rpx' }">
								</image>
							</view>
							<text>{{ menu.name }}</text>
						</view>
					</u-col>
				</u-row>
			</view>


		</view>

		<view class="plr100 mb130 footerClass">
			<button class="btn-box" v-if="token && userInfo.phone" @click="logout">退出登录</button>
			<button class="btn-box" open-type="getAuthorize" scope="userInfo" @getAuthorize="thirdLogin"
				v-else>点击登录</button>


		</view>

		<!--客服电话弹框 -->
		<u-select v-model="showPhone" :safe-area-inset-bottom="true" mode="mutil-column-auto" title="客服电话"
			:list="phoneList" @confirm="phoneconfirm"></u-select>
	</view>
</template>

<script>
	import {
		logout,
		getAutonymResult,
		getUserInfo,
		getBalance,
		getMyMeal,
		promotionGetConfig,
		getMyBattery
	} from '@/api/user.js'
	import {
		getPhone
	} from '@/api/public.js'
	export default {
		data() {
			return {
				agentId: '',
				deviceId: '',
				deviceNo: '',
				yesLogin: '',
				is_autonym: false,

				isEnable: false,
				enableObj: {},
				isMassge: '',
				isDeposit: false,
				promotionId: '',
				userInfoss: [],
				list: {
					balance: 0, //可用余额
					giveMoney: 0, //赠送金额
					deposit: 0, //电池押金
					carDeposit: 0, //车辆押金
				},
				// 客服电话
				showPhone: false,
				phoneList: [],
				phoneValue: '',
				appId: '', //声明小程序的appid为空
				menuList: [

					{
						name: '服务条款',
						path: '/pages/user/service/index',
						icon: '/static/ic_termsOfService.png',
						isLogin: false,
						isOpen: true,
						iconSize: {
							w: '50'
						}
					},
					{
						name: '关于我们',
						path: '/pages/user/service/detail',
						query: {
							type: 6
						},
						icon: '/static/ic_AboutUs.png',
						isLogin: false,
						isOpen: true,
						iconSize: {
							w: '60'
						}
					},
					{
						name: '用户指南',
						path: '/pages/user/service/detail',
						query: {
							type: 5
						},
						icon: '/static/ic_userGuide.png',
						isLogin: false,
						isOpen: true,
						iconSize: {
							w: '60'
						}
					},
					{
						name: '逾期订单',
						path: '/pages/user/myOrder/overdueOrder',
						icon: '/static/ic_overdue.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '52'
						}
					},
					{
						name: '优惠券',
						path: '/pages/user/rentEle/userDiscountCoupon',
						icon: '/static/ic_sblb_02.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '60'
						},
						query: {
							deviceId: ''
						},
					},
					{
						name: '联系客服',
						icon: '/static/ic_phone.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '60'
						}
					},
					{
						name: '电池寄存',
						path: '/pages/user/rentEle/temporaryVolume',
						icon: '/static/ic_BatteryDeposit.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '50'
						}
					},
					{
						name: '意见反馈',
						path: '/pages/user/feedBack/index',
						icon: '/static/iic_opinion.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '52'
						}
					},


					{
						name: '实名认证',
						path: '/pages/user/webview/webview',
						icon: '/static/ic_monitoring.png',
						isLogin: true,
						isOpen: true,
						type: 2,
						iconSize: {
							w: '60'
						}
					},

					{
						name: '推广赚钱',
						path: '/pages/user/extensionActivity/index',
						icon: '/static/ic_promotion.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '60'
						},
						query: {
							promotionId: ''
						},
					},
					{
						name: '退押金',
						path: '/pages/user/wallet/depositDetail',
						icon: '/static/ic_return.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '50'
						},
						query: {
							deviceId: ''
						},
					},
					{
						name: '租电套餐',
						path: '/pages/user/rentEle/package',
						icon: '/static/Electricity_rental_package.png',
						isLogin: true,
						isOpen: true,
						iconSize: {
							w: '50'
						},
						query: {
							deviceNo: '',
							deviceId: '',
						}
					},

				]
			}
		},
		onLoad(e) {
			console.log(e, '页面参数')
			// 实名认证
			if (e.type && (e.type == '1') && e.token) {
				getAutonymResult(e.token)
			}
			let qrCode = getApp().globalData.qrCode;

			if (!qrCode) return
			let qr = this.getUrlPar(qrCode)
			if (e.id) {
				if (!this.token) {
					uni.showToast({
						title: '请登录',
						icon: 'none'
					})
					uni.setStorageSync('promotionId', e.id)
				}
			} else if (qr.promotionId) {
				if (!this.token) {
					uni.showToast({
						title: '请登录',
						icon: 'none'
					})
					uni.setStorageSync('promotionId', qr.promotionId)
				}
			}
		},
		onShow() {
			this.agentId = uni.getStorageSync('oneData').agentId || ''
			this.deviceId = uni.getStorageSync('oneData').deviceId || ''
			this.deviceNo = uni.getStorageSync('oneData').deviceNo || ''
			this.appId = my.getAppIdSync().appId || '' //获取小程序的appid
			this.getUserInfo() //获取用户实名与否
			this.isMassge = this.userInfo.bind_user_id || this.userInfo.yw_id //当有运营商或代理商或运维权限，就打开后台管理1
			if (this.token && this.userInfo.phone) {
				this.moneyVent()
				this.yesLogin = '有值'
				console.log('有值==========');
			} else if (!this.token || !this.userInfo.phone) {
				this.yesLogin = ''
				console.log('没值==========');
			}
			this.getPhoneInfo() // 拿到客服电话
			if (this.yesLogin) {
				if (this.agentId) { //有token与电话是登录的状态，才会请求钱包的信息
					this.getBalance()
				}
			}
			// 获取是不是推广员
			setTimeout(async () => {
				this.promotionId = uni.getStorageSync('PromotionId') || ''
				const fig = await promotionGetConfig() //获取有没有开通小程序申请成为推广员的权限
				this.enableObj = fig.data || {}
				this.isEnable = fig.data.enable == 1 ? true : false
				console.log('推广员id', this.promotionId, '获取有没有开启小程序申请开通推广员权限', this.isEnable ? '开' :
					'没开');
			}, 200)


		},
		computed: {
			token() {
				return this.$store.state.user.token
			},
			userInfo() {
				return this.$store.state.user.userInfo || {}
			},
		},
		watch: {
			//监听 username的值的变化
			//在形参列表中，第一个值是“变化后的新值”，第二个值是“变化前的旧值”
			"token"(newVal, oldVal) {
				console.log('新值', newVal, '旧值', oldVal);
				if (newVal) {
					this.$nextTick(function() {
						console.log('$nextTick');
						setTimeout(() => {
							this.moneyVent()
						}, 500)

					});
				}
			},
		},
		methods: {


			// 修改用户昵称
			buttonPhone() {
				if (!this.token || !this.userInfo.phone) {
					return
				}

			},

			// 拿到客服电话
			async getPhoneInfo() {
				let res = await getPhone({
					appId: this.appId,
					type: 1
				})
				let list = []
				list = res.data || []
				this.phoneList = []
				list.forEach((i) => {
					let obj = {
						value: i.id,
						label: i.areaName,
						children: []
					}
					if (i.phone.split(",").length === 1 || i.phone.split(",").length === 1) {
						obj.children[0] = {
							value: 1,
							label: i.phone.split(",")[0],
						}
					}
					if (i.phone.split(",").length === 2 || i.phone.split(",").length === 2) {
						obj.children[0] = {
							value: 1,
							label: i.phone.split(",")[0],
						}
						obj.children[1] = {
							value: 2,
							label: i.phone.split(",")[1],
						}
					}
					if (i.phone.split(",").length === 3 || i.phone.split(",").length === 3) {
						obj.children[0] = {
							value: 1,
							label: i.phone.split(",")[0],
						}
						obj.children[1] = {
							value: 2,
							label: i.phone.split(",")[1],
						}
						obj.children[2] = {
							value: 3,
							label: i.phone.split(",")[2],
						}
					}
					this.phoneList.push(obj)
					console.log('客服电话', this.phoneList);
				})
			},
			// 选择客服电话
			async phoneconfirm(e) {
				console.log(33444556677, e[1].label);
				this.phoneValue = ''
				this.phoneValue = e[1].label
				this.showPhone = false
				let resultss = await this.confirm({
					content: `确定拨打${this.phoneValue}客服电话？`,
				})
				if (resultss.confirm) {
					uni.makePhoneCall({
						phoneNumber: this.phoneValue //仅为示例
					});

				} else {
					this.toast('已取消拨打')

				}
			},
			//更新钱包数据的方法封装
			moneyVent() {
				this.$store.dispatch('getUserInfo')
				this.userInfoss = this.userInfo.wallet

				this.list.balance = 0
				this.list.giveMoney = 0
				this.list.deposit = 0
				this.list.carDeposit = 0
				this.userInfoss.map((item) => {
					this.list.balance += item.balance
					this.list.giveMoney += item.giveMoney
					this.list.deposit += item.deposit
					this.list.carDeposit += item.carDeposit
				})
				if (this.list.deposit !== 0) {
					this.isDeposit = true
				} else {
					this.isDeposit = false
				}
			},
			// 钱包
			async getBalance() {
				const res = await getBalance()
				this.userInfoss = res.data || []
				console.log('+++++++++', this.userInfoss);
				this.list.balance = 0
				this.list.giveMoney = 0
				this.list.deposit = 0
				this.list.carDeposit = 0
				if (this.userInfoss.length !== 0) {
					this.userInfoss.forEach((item) => {
						this.list.balance += item.balance
						this.list.giveMoney += item.giveMoney
						this.list.deposit += item.deposit
						this.list.carDeposit += item.carDeposit
					})
					if (this.list.deposit !== 0) {
						this.isDeposit = true
					} else {
						this.isDeposit = false
					}
				}

			},
			// 菜单栏
			async routerListFn(menu) {
				if (menu.name === '联系客服') {
					this.showPhone = true
				}
				if (menu.name === '优惠券') {
					if (this.deviceId) {
						menu.query.deviceId = this.deviceId
					} else {
						this.toast('请先扫设备码再使用')
						return false
					}
				}
				if (menu.name === '电池寄存') {
					if (this.agentId) {
						console.log('agentId', this.agentId);
					} else {
						this.toast('请先扫设备码再使用')
						return false
					}
					if (this.deviceId) {
						const res = await getMyMeal({
							deviceId: this.deviceId
						})
						if (!res.data) {
							this.toast('请先购买套餐再使用')
							return false
						}
					} else {
						this.toast('请先购买套餐再使用')
					}
					// 查询用户手上有没有电池，没有就不让寄存
					const getMy = await getMyBattery()
					if (getMy.code == 200) {
						console.log('有电池在手');
					} else {
						this.toast('请先租电，还电池时再使用寄存')
						return false
					}
				}
				if (menu.name === '推广赚钱') {
					// 如果有推广id，就是在pc端设置为推广员或在小程序已经申请为推广员了，就直接进去推广页面
					if (this.promotionId) {
						menu.path = '/pages/user/extensionActivity/index'
					} else { //如果没有推广员id，但是开启在小程序端可以开通成为推广员的权限，就进入申请页面
						if (this.isEnable) {
							menu.query.amount = this.enableObj.amount || 0
							menu.query.ruleNumber = this.enableObj.ruleNumber || 0
							menu.path = '/pages/user/extensionActivity/applyFor'
						} else {
							this.toast('该商户暂未开通此功能')
							return false
						}
					}
				}

				if (menu.name === '租电套餐') {
					if (!this.deviceId || !this.deviceNo) {
						this.toast('请先扫设备码再使用')
						return false
					}
					menu.query.deviceNo = this.deviceNo
					menu.query.deviceId = this.deviceId
				}
				if (menu.name === '退押金') {
					if (!this.isDeposit) {
						this.toast('暂无押金，请交付押金后再退')
						return false
					}
				}
				if (menu.name === '实名认证') {
					if (this.is_autonym) {
						this.toast('你已经实名认证过！')
						return false
					} else {
						uni.showModal({
							title: '提示',
							content: '请实名认证',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/user/webview/webview'
									})
								}
							}
						});
					}
				}
				if (menu.name !== '实名认证') {
					this.routerLink({
						path: menu.path,
						query: menu.query,
					}, menu.isLogin)
				}

			},
			// 退出登录
			async logout() {
				let result = await this.confirm({
					content: '确定退出登录？'
				})
				if (result.confirm) {
					const res = await logout()
					this.$store.commit('login', '')
					this.$store.commit('setUserInfo', {})
					this.userInfo = {}
					this.yesLogin = ''
				}
			},
			// 立即充值
			async RechargeImmediately() {
				if (!this.agentId) {
					return this.toast('请先扫设备二维码再充值')
				}
				if (this.userInfoss[0].depositStatus !== 1) {
					return this.toast('请先交付电池押金再充值')
				}

				await this.routerLink({
					path: '/pages/user/wallet/recharge'
				})

			},
			// 我的钱包
			nomeybaoFn() {
				if (this.userInfoss[0].depositStatus !== 1) {
					return this.toast('请先交付电池押金再进入')
				}
				this.routerLink({
					path: '/pages/user/wallet/index'
				}, true)
			},
			// 获取用户实名与否
			async getUserInfo() {
				let res = await getUserInfo()
				if (res.code === 200) {
					this.is_autonym = res.data.is_autonym || false
					uni.setStorageSync('PromotionId', res.data.promotion_id || '')
				}
			},
			// 处理推广二维码
			getUrlPar(url) {
				let params = url.split("?")[1].split("&");
				let obj = {};
				params.map(v => (obj[v.split("=")[0]] = v.split("=")[1]));
				return obj
			},
		}
	}
</script>

<style lang="scss" scoped>
	.displayss {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}

	.pure_top {
		position: relative;
		width: 100%;
		height: 300upx;
		background-color: $primary;

		&::after {
			position: absolute;
			left: -10%;
			bottom: -25upx;
			z-index: -2;
			content: '';
			width: 100%;
			height: 100upx;
			border-radius: 0 0 50% 50%;
			background: $primary;
		}
	}

	.center_c {
		position: relative;
		top: -100upx;
		// margin-bottom: 100upx;
	}

	.btn-box {
		color: #fff;
		background-color: #3282FF;
		border-radius: 50rpx;
	}

	.body_flex {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.box_flex {
		width: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.one {
		padding-left: 40rpx;
		padding-right: 40rpx;
		padding-top: 30rpx;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 0 8px 1px #e5e5e5;
	}

	.mgbt {
		margin-bottom: 40rpx;
	}

	.footerClass {
		position: relative;
		top: -30upx;
	}
</style>